<!--_meta 作为公共模版分离出去-->
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <link rel="Bookmark" href="/favicon.ico">
    <link rel="Shortcut Icon" href="/favicon.ico"/>
    <!--[if lt IE 9]-->
    <script type="text/javascript" src="lib/html5shiv.js"></script>
    <script type="text/javascript" src="lib/respond.min.js"></script>
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="static/h-ui/css/H-ui.min.css"/>
    <link rel="stylesheet" type="text/css" href="lib/At.js-master/css/jquery.atwho.css"/>
    <link rel="stylesheet" type="text/css" href="static/h-ui.admin/css/H-ui.admin.css"/>
    <link rel="stylesheet" type="text/css" href="lib/Hui-iconfont/1.0.8/iconfont.css"/>
    <link rel="stylesheet" type="text/css" href="static/h-ui.admin/skin/default/skin.css" id="skin"/>
    <link rel="stylesheet" type="text/css" href="static/h-ui.admin/css/style.css"/>
    <!--[if IE 6]-->
    <script type="text/javascript" src="lib/DD_belatedPNG_0.0.8a-min.js"></script>
    <script>DD_belatedPNG.fix('*');</script>
    <![endif]-->
    <!--/meta 作为公共模版分离出去-->
    <title>用例编辑</title>
</head>
<body>
<article class="page-container">
    <form method="post" class="form form-horizontal" id="form">
        <div class="row cl" style="display:none">
            <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>服务：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <span class="select-box">
                    <select class="select" size="1" name="service" id="service"></select>
				</span>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>接口：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <input type="text" class="input-text" value="" placeholder="" id="ti" name="ti" disabled="disabled">
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>用例名称：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <input type="text" class="input-text" value="" placeholder="用例名称" id="caseName" name="caseName">
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3">用例描述：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <input type="text" class="input-text" value="" placeholder="用例描述" id="remark" name="remark">
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3">环境：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <span class="select-box">
                    <select class="select" size="1" name="env" id="env">
                        <option value="0" selected>请选择环境</option>
                    </select>
				</span>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3">测试类：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <span class="select-box">
                    <select class="select" size="1" name="testclass" id="testclass">
                        <option value="" selected>请选择测试类</option>
                    </select>
				</span>
            </div>
        </div>

        <div class="row cl" id="headerDiv" name="headerDiv" style="display: none">
            <label class="form-label col-xs-4 col-sm-3">请求Headers：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <textarea id="headerText" name="headerText" cols="" rows="" class="textarea valid"
                          placeholder="" style="width:80%;"></textarea>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3">请求参数：</label>
            <div id="request1" class="formControls col-xs-8 col-sm-9">
                <textarea id="requestParam" name="requestParam" cols="" rows="" class="textarea valid"
                          placeholder="请输入请求参数..."></textarea>
                <!--<pre id="requestParam"></pre>-->
            </div>
            <div id="paramInput1" class="formControls col-xs-8 col-sm-9" hidden>
                <table id="paramTable" style="width: 86%;">
                </table>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>断言类型：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <span class="select-box">
                    <select class="select" size="1" name="assertType" id="assertType" onchange="assertTypeChage()">
                        <option value="" selected>请选择断言类型</option>
                    </select>
				</span>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3">期望结果：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <textarea id="expected" name="expected" cols="" rows="" class="textarea valid"
                          placeholder=""></textarea>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3">后置处理：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <textarea id="cafter" name="cafter" cols="" rows="" class="textarea valid"
                          placeholder="此用例运行完成后处理的内容"></textarea>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-3">设计人：</label>
            <div class="formControls col-xs-8 col-sm-9">
                <input type="text" class="input-text" value="" placeholder="" id="author" name="author"
                       disabled="disabled">
            </div>
        </div>
        <div class="row cl">
            <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3" id="submit">

            </div>
        </div>
    </form>
</article>

<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" src="static/hry-auto/util.js"></script>
<script type="text/javascript" src="lib/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="lib/layer/2.4/layer.js"></script>
<script type="text/javascript" src="static/h-ui/js/H-ui.min.js"></script>
<script type="text/javascript" src="static/h-ui.admin/js/H-ui.admin.js"></script> <!--/_footer 作为公共模版分离出去-->

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="lib/jquery.validation/1.14.0/jquery.validate.js"></script>
<script type="text/javascript" src="lib/jquery.validation/1.14.0/validate-methods.js"></script>
<script type="text/javascript" src="lib/jquery.validation/1.14.0/messages_zh.js"></script>
<script type="text/javascript" src="lib/At.js-master/js/jquery.atwho.js"></script>
<script type="text/javascript" src="lib/At.js-master/js/jquery.caret.js"></script>
<script type="text/javascript">
    var layerIndex;
    //loading
    /*$(function () {
        $.ajaxSetup({
            layerIndex: -1,
            beforeSend: function () { //插件加载前
                layerIndex = layer.load(1, {shade: [1.01, '#fff']});
                $('#admin-role-save').val("正在提交请稍等...")
            },
            error: function () { //报错时执行
                layer.alert('显示异常，请刷新后重试', {
                    skin: 'layui-layer-molv'
                    , closeBtn: 0
                    , shift: 4 //动画类型
                });
            }
        });
    });*/

    var iId;
    var cId;
    var skip;
    //页面加载处理
    $(document).ready(function () {
        cId = getParameter('id');
        skip = getParameter('skip');
        $("#id").val(cId);
        var assertTypeList = getAssertType();
        var envList = getTenvList();
        $.ajax({
            type: "post",
            url: "/tcase/selectOne",
            data: {
                id: cId
            },
            dataType: "json",
            success: function (data) {
                var status = data.status;
                var msg = data.msg;
                var tcase = data.data;

                if (status == 0) {
                    iId = tcase.iid;

                    //服务
                    var tservice = getServiceByServiceId(tcase.serviceid);
                    $("#service").append("<option value=\"" + tservice.id + "\" selected>" + tservice.servicekey + "</option>");

                    //接口
                    var ti = getTiById(tcase.iid);
                    $("#ti").val(ti.iuri + "(" + ti.remark + ")");

                    //用例名称
                    $("#caseName").val(tcase.casename);
                    //用例描述
                    $("#remark").val(tcase.remark == null ? "" : tcase.remark);

                    //环境
                    var envHtml = "";
                    for (var k = 0; k < envList.length; k++) {
                        envHtml += "<option value=\"" + envList[k].id + "\">" + envList[k].envkey + "</option>";
                    }
                    $("#env").append(envHtml);
                    $("#env").val(tcase.envid != null ? tcase.envid : 0);

                    //测试类
                    var testclassList = getClassesBySId(tcase.serviceid);
                    var testclassHtml = "";
                    for (var i = 0; i < testclassList.length; i++) {
                        testclassHtml += "<option value=\"" + testclassList[i] + "\">" + testclassList[i] + "</option>";
                    }
                    $("#testclass").append(testclassHtml);
                    if (tcase.testclass != null) {
                        $("#testclass").val(tcase.testclass);
                    }

                    //请求header
                    var tcaseRequesHeader = tcase.requestheader;
                    var tiHeaderSample = ti.iheadersample;
                    if (tiHeaderSample != null && tiHeaderSample.length > 0) {
                        $("#headerDiv").show();
                        if (tcaseRequesHeader != null && tcaseRequesHeader != "") {
                            $("#headerText").val(JSON.stringify(JSON.parse(tcaseRequesHeader), null, 2));
                        }
                    }

                    //请求参数
                    var requestparam = "";
                    //调用requestParam的<触发事件
                    //setRequestParameter();
                    if (tcase.requestparam != null) {
                        requestparam = tcase.requestparam;
                    }
                    var iparamtype = ti.iparamtype;
                    if(iparamtype == 1){
                        document.getElementById("request1").style.display = "block";
                        document.getElementById("paramInput1").style.display = "none";
                        $("#paramTable").find("tr").remove();

                        if (requestparam != null && requestparam.length > 0) {

                            try {
                                var requestJson = JSON.stringify(JSON.parse(requestparam), null, 2);
                                $("#requestParam").val(requestJson);
                            } catch (e) {
                                $("#requestParam").val(requestparam);
                            }
                        }else{
                            $("#requestParam").val(requestparam);
                        }

                    } else if(iparamtype == 2) {//请求参数类型为map处理逻辑

                        changeByParamType(requestparam);
                    }else{//请求参数类型为map处理逻辑
                        $("#requestParam").val(requestparam);
                    }

                   /* if (requestparam != null && requestparam.length > 0 && iparamtype == 1) {
                        try {
                            var requestparamJson = JSON.stringify(JSON.parse(requestparam), null, 2);
                            $("#requestParam").val(requestparamJson);
                        } catch (e) {
                            $("#requestParam").val(requestparam);
                        }
                    } else {
                        $("#requestParam").val(requestparam);
                    }*/
                    //断言类型
                    var assertTypeHtml = "";
                    for (var k = 0; k < assertTypeList.length; k++) {
                        assertTypeHtml += "<option value=\"" + assertTypeList[k].id + "\">" + assertTypeList[k].value + "</option>";
                    }
                    $("#assertType").append(assertTypeHtml);
                    $("#assertType").val(tcase.asserttype);


                    //期望结果
                    var expected = tcase.expected;
                    if (expected == null) {
                        expected = "";
                    }
                    if (tcase.asserttype == 3) {
                        try {
                            var requestJson = JSON.stringify(JSON.parse(expected), null, 2);
                            $("#expected").val(requestJson);
                        } catch (e) {
                            console.log("异常走到Catch了")
                            $("#expected").val(expected);
                        }
                    } else {
                        $("#expected").val(expected);
                    }

                    //后置处理
                    if (tcase.cafter != null) {
                        $("#cafter").val(tcase.cafter);
                    }

                    //用例设计人
                    $("#author").val(tcase.author);
                    //提交按钮处理

                    var submit = "<button type=\"button\" class=\"btn btn-success radius\" id=\"admin-role-save\" name=\"admin-role-save\" onclick=\"editTcase(" + cId + ","+iparamtype+")\"><i class=\"icon-ok\"></i> 提交</button>" +
                        "<button type=\"button\" style='margin-left:5px;' class=\"btn btn-success radius\" id=\"admin-role-run\" name=\"admin-role-run\" onclick=\"runTcase("+iparamtype+")\"><i class=\"icon-ok\"></i> 测试</button>" +
                        "<button type=\"button\" style='margin-left:5px;' class=\"btn btn-success radius\" id=\"admin-role-close\" name=\"admin-role-close\" onclick=\"layer_close()\"><i class=\"icon-ok\"></i>关闭</button>";
                    $("#submit").append(submit);

                    var tauthor = tcase.author;
                    var realName = $.cookie('realnameCookie');

                    if (tauthor != realName){
                        $('#admin-role-save').attr("disabled",true);
                        $('#admin-role-save').css("background-color","#ebebe4");
                        $('#admin-role-save').css("border-color","#ebebe4");
                        $('#admin-role-save').attr("title","非本人用例不能编辑");
                    }
                    layer.close(layerIndex);
                } else {
                    layer.close(layerIndex);
                    layer.alert(msg, {
                        icon: 0,
                        skin: 'layer-ext-moon'
                    });
                }


            }

        });
        //调用requestParam的<触发事件
        setRequestParameter();

    });

    //请求参数实例动态增加输入框处理
    function addInput(){
        var rows=document.getElementById("paramTable").rows.length;
        var row=rows+1;
        var html="<tr id='tr"+row+"'>\n" +
            "                        <td style='width: 30%'><input type=\"text\" class=\"input-text\" value=\"\" placeholder=\"key\" id=\"key"+row+"\" name=\"key"+row+"\"></td>\n" +
            "                        <td style='width: 55%;'>\n" +
            "                            <input type=\"text\" class=\"input-text\" value=\"\" placeholder=\"value\" id=\"value"+row+"\" name=\"value"+row+"\">\n" +
            "                            <a href=\"javascript:;\" onclick=\"addInput()\"><i class=\"Hui-iconfont\">&#xe600;</i></a><a href='javascript:;' onclick='clearInput("+row+")'><i class=\"Hui-iconfont\">&#xe6a1;</i></a>\n" +
            "                        </td>\n" +
            "                    </tr>";

        $("#paramTable").append(html);
        //调用requestParam的<触发事件
        setRequestParameter();

    }

    //动态减少输入框处理
    function clearInput(row){
        document.getElementById("tr"+row).remove();

    }

    //根据请求参数类型不同更改请求参数展示方式
    function changeByParamType(iparamsample){
        document.getElementById("request1").style.display = "none";
        document.getElementById("paramInput1").style.display = "block";
        var inputHtml="";
        if(iparamsample == '{}'){
            inputHtml = "<tr id='tr1'>\n" +
                "                        <td style='width: 30%'><input type=\"text\" class=\"input-text\" value=\"\" placeholder=\"key\" id=\"key1\" name=\"key1\"></td>\n" +
                "                        <td style='width: 55%;'>\n" +
                "                            <input type=\"text\" class=\"input-text\" value=\"\" placeholder=\"value\" id=\"value1\" name=\"value1\">\n" +
                "                            <a href=\"javascript:;\" onclick=\"addInput()\"><i class=\"Hui-iconfont\">&#xe600;</i></a>\n" +
                "                        </td>\n" +
                "                    </tr>";
            $("#paramTable").append(inputHtml);

        }else{
            var iparamDemo=JSON.parse(iparamsample);
            console.log("请求参数为："+iparamsample);
            var num=0;
            for(var key in iparamDemo) {
                var value = iparamDemo[key];
                num++;
                if (num == 1) {
                    inputHtml += "<tr id='tr" + num + "'>\n" +
                        "                        <td style='width: 30%'><input type=\"text\" class=\"input-text\" value=\"" + key + "\" placeholder=\"key\" id=\"key" + num + "\" name=\"key" + num + "\"></td>\n" +
                        "                        <td style='width: 55%;'>\n" +
                        "                            <input type=\"text\" class=\"input-text\" value=\"" + value + "\" placeholder=\"value\" id=\"value" + num + "\" name=\"value" + num + "\">\n" +
                        "                            <a href=\"javascript:;\" onclick=\"addInput()\"><i class=\"Hui-iconfont\">&#xe600;</i></a><a href='javascript:;' onclick='clearInput(" + num + ")'></a>\n" +
                        "                        </td>\n" +
                        "                    </tr>";
                } else {

                    console.log("key="+key+",value="+value);

                    //某个key的值还是json对象格式，要以字符串格式在前端展示，双引号要加\转义
                    /*if(value != '' && value != null){
                        if(isJsonString(value)){
                            //value = JSON.stringify(value).replace(/"/g, '\"')
                            value = value.replace(/"/g, '\"');
                            //alert(key+"的值是json对象");
                        }
                        console.log("key="+key+",value="+value);

                    }*/
                    inputHtml += "<tr id='tr" + num + "'>\n" +
                        "                        <td style='width: 30%'><input type=\"text\" class=\"input-text\" value=\"" + key + "\" placeholder=\"key\" id=\"key" + num + "\" name=\"key" + num + "\"></td>\n" +
                        "                        <td style='width: 55%;'>\n" +
                        "                            <input type=\"text\" class=\"input-text\" value=\'" + value+ "\' placeholder=\"value\" id=\"value" + num + "\" name=\"value" + num + "\">\n" +
                        "                            <a href=\"javascript:;\" onclick=\"addInput()\"><i class=\"Hui-iconfont\">&#xe600;</i></a><a href='javascript:;' onclick='clearInput(" + num + ")'><i class=\"Hui-iconfont\">&#xe6a1;</i></a>\n" +
                        "                        </td>\n" +
                        "                    </tr>";
                }
            }
            $("#paramTable").append(inputHtml);
        }


    }

    //断言类型改变处理
    function assertTypeChage() {
        var assertType = $("#assertType").val();
        var assertTypeList = getAssertType();
        var placeholder = "";
        for (var i = 0; i < assertTypeList.length; i++) {
            var row = assertTypeList[i];
            if (row.id == assertType) {
                placeholder = row.desc;
                $("#expected").prop("placeholder", placeholder);
                break;
            } else {
                $("#expected").prop("placeholder", "");
            }
        }


    }

    //编辑用例
    function editTcase(id,paramType) {
        var caseName = $("#caseName").val();
        var remark = $("#remark").val();
        var env = $("#env").val();
        var service = $("#service").val();
        var requestHeader = $("#headerText").val();
        var requestParam;
        if(paramType == 2){

            var table=document.getElementById("paramTable");
            var rows=table.rows;
            var json;

            json = "{";
            for(i=0;i<rows.length;i++){
                var rowList=rows[i].getElementsByTagName("input");
                if(rowList[0].value.length>0 || rowList[1].value.length>0){
                    var key=rowList[0].value;
                    var value=rowList[1].value;

                    //某个key的值还是json对象格式，不用加双引号
                    if(isJsonString(value)){

                        json+='\"'+key+'\"'+':'+JSON.stringify(value)+',';

                        }else{

                        json+='\"'+key+'\"'+':\"'+value+'\",';
                    }

                }

            }
            if(json.length>1){
                json = json.substring(0, json.length-1);
            }

            json+="}";
            requestParam=json;

        }else{
            requestParam = $("#requestParam").val();
        }

        var assertType = $("#assertType").val();
        var expected = $("#expected").val();
        var cafter = $("#cafter").val();
        //var author = $("#author").val();
        var author = $.cookie("realnameCookie");
        var testclass = $("#testclass").val();


        if (caseName == null || caseName == "") {
            layer.alert("用例名称不能为空！");
            return;
        } /*else if (ti == null || ti == "") {
            layer.alert("请选择接口！");
            return;
        }*/ else if (assertType == null || assertType == "") {
            layer.alert("请选择断言类型！");
            return;
        } else {
            $.ajax({
                type: 'POST',
                url: '/tcase/updateOne',
                data: {
                    id: id,
                    casename: caseName,
                    remark: remark,
                    serviceid: service,
                    iid: iId,
                    envid: env,
                    testclass: testclass,
                    requestheader: requestHeader,
                    requestparam: requestParam,
                    asserttype: assertType,
                    expected: expected,
                    cafter: cafter,
                    author: author,
                    // status: 1  //状态不必传,所有的状态,都是通过操作改变,不可通过定义改变
                },
                dataType: 'json',
                success: function (data) {
                    var status = data.status;
                    var msg = data.msg;

                    if (status == 0) {
                        //parent.window.location.reload();
                        if (skip != '1') {
                            window.parent.pageSkip(1);
                        }
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    } else {
                        layer.close(layerIndex);
                        layer.alert(msg, {
                            icon: 0,
                            skin: 'layer-ext-moon'
                        });
                    }

                },
                error: function (xhr) {
                    layer.close(layerIndex);
                    layer.alert('Error' + JSON.stringify(xhr), {
                        icon: 2,
                        skin: 'layer-ext-moon'
                    });
                },
            });
        }

    }

    //运行用例
    function runTcase(paramType) {
        var caseName = $("#caseName").val();
        var remark = $("#remark").val();
        var env = $("#env").val();
        var service = $("#service").val();
        var requestHeader = $("#headerText").val();
        var requestParam;
        if(paramType == 2){

            var table=document.getElementById("paramTable");
            var rows=table.rows;
            var json;

            json = "{";
            for(i=0;i<rows.length;i++){
                var rowList=rows[i].getElementsByTagName("input");
                if(rowList[0].value.length>0 || rowList[1].value.length>0){
                    var key=rowList[0].value;
                    var value=rowList[1].value;

                    //某个key的值还是json对象格式，不用加双引号
                    if(isJsonString(value)){

                        json+='\"'+key+'\"'+':'+JSON.stringify(value)+',';

                    }else{

                        json+='\"'+key+'\"'+':\"'+value+'\",';
                    }

                }

            }
            if(json.length>1){
                json = json.substring(0, json.length-1);
            }

            json+="}";
            requestParam=json;

        }else{
            requestParam = $("#requestParam").val();
        }

        var assertType = $("#assertType").val();
        var expected = $("#expected").val();
        var cafter = $("#cafter").val();
        var testClass = $("#testclass").val();
        var userId = $.cookie('uidCookie');

        if (iId == null || iId == "") {
            layer.alert("请选择接口！");
            return;
        } else if (assertType == null || assertType == "") {
            layer.alert("请选择断言类型！");
            return;
        } else {
            $.ajax({
                type: "post",
                url: "/tcase/runCase",
                data: {
                    casename: caseName,
                    remark: remark,
                    serviceid: service,
                    iid: iId,
                    envid: env,
                    requestheader: requestHeader,
                    requestparam: requestParam,
                    asserttype: assertType,
                    expected: expected,
                    cafter: cafter,
                    testclass: testClass,
                    userId: userId
                },
                dataType: "json",
                success: function (data) {
                    var url = data.data;
                    var status = data.status;
                    var msg = data.msg;
                    if (status == 0) {
                        layer.close(layerIndex);
                        var tiName = $("#ti").val();
                        url = encodeURI("../report-loading.html?reportname=" + url + "&customname=" + tiName);
                        window.open(url);

                        /* var domain = "http://"+window.location.host;
                         var myPopup = window.open("test-result.html");//.postMessage(list,domain);
                         //周期性的发送消息
                         setTimeout(function(){
                             myPopup.postMessage(list,domain);
                         },1000);*/

                        /* layer.alert(msg);
                         parent.window.location.reload();
                         var index = parent.layer.getFrameIndex(window.name);
                         parent.layer.close(index);*/
                    } else {
                        layer.close(layerIndex);
                        layer.alert(msg, {
                            icon: 0,
                            skin: 'layer-ext-moon'
                        });
                    }

                },
                fail: function (data) {
                    layer.close(layerIndex);
                    layer.alert(JSON.stringify(data), {
                        icon: 0,
                        skin: 'layer-ext-moon'
                    });
                },
                error: function (xhr) {
                    layer.close(layerIndex);
                    layer.alert('Error' + JSON.stringify(xhr), {
                        icon: 2,
                        skin: 'layer-ext-moon'
                    });
                }
            });
        }


    }

</script>

</body>
</html>